import { ref } from 'vue'

export default function useInteractive () {
  const currentShow = ref('cd')
  const middleLStyle = ref(null)
  const middleRStyle = ref(null)

  // 区别于currentShow，currentShow在滑动时会改变，而currentView是停止才确定
  let currentView = 'cd'
  const touch = {}

  function onMiddleTouchStart (e) {
    touch.startX = e.touches[0].pageX
    touch.startY = e.touches[0].pageY
    // 定义滚动方向，防止滑动歌词时可以斜着划
    touch.scrollDirection = ''
  }
  function onMiddleTouchMove (e) {
    // 计算滑动偏移量
    const deltaX = e.touches[0].pageX - touch.startX
    const deltaY = e.touches[0].pageY - touch.startY

    // 判断横竖那个偏移量大
    const absDeltaX = Math.abs(deltaX)
    const absDeltaY = Math.abs(deltaY)
    // 初始化方向锁
    if (!touch.scrollDirection) {
      touch.scrollDirection = absDeltaX > absDeltaY ? 'h' : 'v'
    }
    // 如果是y偏移大，那就不横向滚动
    if (touch.scrollDirection === 'v') {
      return
    }
    // middle-r出现的宽度
    const left = currentView === 'cd' ? 0 : -window.innerWidth
    const offsetWidth = Math.min(0, Math.max(-window.innerWidth, left + deltaX))
    // 滑动比例
    touch.percent = Math.abs(offsetWidth / window.innerWidth)
    // 如果当前显示为cd，则向左滑动超过0.2就显示lyric
    if (currentView === 'cd') {
      if (touch.percent > 0.2) {
        currentShow.value = 'lyric'
      } else {
        currentShow.value = 'cd'
      }
    } else {
      if (touch.percent < 0.8) {
        currentShow.value = 'cd'
      } else {
        currentShow.value = 'lyric'
      }
    }
    middleLStyle.value = {
      opacity: 1 - touch.percent
    //   transitionDuration: '0ms'
    }
    middleRStyle.value = {
      transform: `translateX(${offsetWidth}px)`
    //   transitionDuration: '0ms'
    }
  }
  function onMiddleTouchEnd () {
    let offsetWidth
    let opacity
    if (currentShow.value === 'cd') {
      currentView = 'cd'
      offsetWidth = 0
      opacity = 1
    } else {
      currentView = 'lyric'
      offsetWidth = -window.innerWidth
      opacity = 0
    }
    middleLStyle.value = {
      opacity: opacity,
      transitionDuration: '300ms'
    }
    middleRStyle.value = {
      transform: `translateX(${offsetWidth}px)`,
      transitionDuration: '300ms'
    }
  }
  return {
    currentShow,
    middleLStyle,
    middleRStyle,
    onMiddleTouchStart,
    onMiddleTouchMove,
    onMiddleTouchEnd
  }
}
